<?php

/**
 * Author: Jesse
 * Email : jessedev@163.com
 * Date: 2024/6/14 22:29
 * FileName: ConfigClient.php
 * DESC: The Relentless Pursuit of Perfection.
 */

namespace Common\Kernel\Nacos;

use Hyperf\ConfigNacos\Client as BaseConfigNacosClient;

/**
 * 配置中心客户端
 */
class ConfigClient extends BaseConfigNacosClient
{
    /**
     * 拉去配置
     *
     * @return array
     */
    public function pull(): array
    {
        $listener = $this->config->get('config_center.drivers.nacos.listener_config', []);
        $defaultConfigKey = $this->config->get('config_center.drivers.nacos.default_key');

        $config = [];
        foreach ($listener as $key => $item) {
            $dataId = $item['data_id'];
            $group = $item['group'];
            $tenant = $item['tenant'] ?? null;
            $type = $item['type'] ?? null;
            $response = $this->client->config->get($dataId, $group, $tenant);
            if ($response->getStatusCode() !== 200) {
                $this->logger->error(sprintf('The config of %s read failed from Nacos.', $key));
                continue;
            }

            # 获取配置中心的配置
            $nacosConfig = $this->decode((string)$response->getBody(), $type);

            # 默认覆盖配置，改为合并配置
            if ($key == $defaultConfigKey) {
                # 使用默认配置可以配置所有的配置文件
                $config = array_merge_recursive($config, $nacosConfig);
            } else {
                # 单个文件配置
                $config[$key] = array_merge_recursive($config[$key] ?? [], $nacosConfig);
            }
        }

        return $config;
    }
}